//配置数据库:
let mysql = require('mysql');
let connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database: 'blog'
})
connection.connect()



//定义模块来处理新用户注册事件:
module.exports = {

    //查询信息:
    getUserByName: (username, cb) => {
        let sqlStr = 'select * from user where username = ?';
        connection.query(sqlStr, [username], (err, results) => {
            if (err) return cb(err, null)
            cb(null, results)
        })
    },
    //-----------新增信息:
    //newuser : 表单数据:
    //cb : 回调函数
    addNewUser: (newuser, cb) => {
        //sql语句: //拿到新用户表单数据以后,添加到数据库:
        let sqlStr = 'insert into user set ?';
        //操作数据库:
        //传入的一第一个参数是sql语句,第二个是需要操作的数据:
        connection.query(sqlStr, newuser, (err, results) => {
            //失败:
            if (err) return cb(err, null);
            //否则成功:
            cb(null, results)
        })
    },

    //登陆查询数据库是否有此信息:
    checkLogin: (user, cb) => {
        //sql语句:
        let sqlStr = 'select * from user where username = ? and password = ?';
        //连接数据库查询：
        connection.query(sqlStr, [user.username, user.password], (err, results) => {
            //查询失败:
            if (err) return cb(err, null);
            //查询成功:
            cb(null, results)

        })
    }
}